from pathlib import Path

from environ import Env
from loguru import logger

BASE_DIR = Path(__file__).resolve().parent.parent
LOG_DIR = BASE_DIR / 'logs'

DEBUG = True

# Path
logger.add(
    sink=LOG_DIR / '{time:YYYY-MM-DD}.log',
    rotation="00:00",
    retention="3 days",
    compression="gz",
    encoding="utf-8",
    enqueue=True
)

# Env
assert (env_file_path := BASE_DIR / 'develop.env' if DEBUG else BASE_DIR / 'produce.env').is_file(), '缺少环境变量文件'
logger.info(f'环境变量:{env_file_path.name}')
env = Env(
    SUBSCRIPTION_TIPS_NUM_ORIGIN_ID=(str, ''),  # 每日推送测试订阅号原始id
    SUBSCRIPTION_TIPS_NUM_APP_ID=(str, ''),  # 每日推送测试订阅号app_id
    SUBSCRIPTION_TIPS_NUM_APP_NAME=(str, ''),  # 每日推送公众号名称
    SUBSCRIPTION_TIPS_NUM_APP_SECRET=(str, ''),  # 每日推送测试订阅号app_secret
    SUBSCRIPTION_TIPS_NUM_TOKEN=(str, ''),  # 每日推送测试订阅号消息token
    SUBSCRIPTION_TIPS_NUM_ENCODING_AES_KEY=(str, ''),  # 每日推送测试订阅号消息AES key
    SUBSCRIPTION_TIPS_NUM_CAN_GET_USER_INFO=(int, 0),  # 每日推送测试订阅号是否能够查询用户信息

    SUBSCRIPTION_BEACHBURG_NUM_ORIGIN_ID=(str, ''),  # 比奇堡订阅号原始id
    SUBSCRIPTION_BEACHBURG_NUM_APP_ID=(str, ''),  # 比奇堡订阅号app_id
    SUBSCRIPTION_BEACHBURG_NUM_APP_NAME=(str, ''),  # 比奇堡订阅号公众号名称
    SUBSCRIPTION_BEACHBURG_NUM_APP_SECRET=(str, ''),  # 比奇堡订阅号app_secret
    SUBSCRIPTION_BEACHBURG_NUM_TOKEN=(str, ''),  # 比奇堡订阅号消息token
    SUBSCRIPTION_BEACHBURG_NUM_ENCODING_AES_KEY=(str, ''),  # 比奇堡订阅号消息AES key
    SUBSCRIPTION_BEACHBURG_NUM_CAN_GET_USER_INFO=(int, 0),  # 比奇堡订阅号是否能够查询用户信息

    MINIPROGRAM_APP_ID=(str, ''),  # 小程序app_id
    MINIPROGRAM_APP_SECRET=(str, ''),  # 小程序app_secret

    DAILY_TEMPLATE=(str, ''),  # 每日推送模板id
    TOKEN_WARNING_TEMPLATE=(str, ''),  # access_token刷新失败警告模板id
    VERSION_UPDATE_TEMPLATE=(str, ''),  # 版本更新公告模板id
    MESSAGE_PUSH_TEMPLATE=(str, ''),  # 消息推送模板id

    REDIS_HOST=(str, ''),  # redis host
    REDIS_PORT=(str, ''),  # redis 端口
    REDIS_PWD=(str, ''),  # redis 密码
    REDIS_DB=(str, ''),  # redis 库

    MYSQL_HOST=(str, ''),  # mysql host
    MYSQL_PORT=(str, ''),  # mysql 端口
    MYSQL_USERNAME=(str, ''),  # mysql 用户名
    MYSQL_PASSWORD=(str, ''),  # mysql 密码
    MYSQL_DATABASE=(str, ''),  # mysql 正式数据库名称
    MYSQL_TEST_DATABASE=(str, ''),  # mysql 测试数据库名称

    BAIDU_MAP_AK=(str, ''),  # 百度地图Key
)
Env.read_env(env_file=str(env_file_path))

# SERVICE CONSTANT
SERVICE_BASE_INFO = {
    'subscription_tips': {
        'app_id': env('SUBSCRIPTION_TIPS_NUM_APP_ID'),
        'app_secret': env('SUBSCRIPTION_TIPS_NUM_APP_SECRET')
    },
    'subscription_beachburg': {
        'app_id': env('SUBSCRIPTION_BEACHBURG_NUM_APP_ID'),
        'app_secret': env('SUBSCRIPTION_BEACHBURG_NUM_APP_SECRET')
    },
    'miniprogram': {
        'app_id': env('MINIPROGRAM_APP_ID'),
        'app_secret': env('MINIPROGRAM_APP_SECRET')
    },
}

SECRET_KEY = 'django-insecure-xh6#i#ltb_p&u5f06((u7+=by2vq_+bmiz#c_5p=-)8d#pdgkz'

ALLOWED_HOSTS = ['*']

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app_mini_program',
    'app_subscription_account',
    'app_management',
    'app_web',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'beachburg_joint_plan.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'beachburg_joint_plan.wsgi.application'

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False

STATIC_URL = '/static/'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

SUBSCRIPTION_INFO = {
    env('SUBSCRIPTION_TIPS_NUM_ORIGIN_ID'): {
        'app_name': env('SUBSCRIPTION_TIPS_NUM_APP_NAME'),
        'app_id': env('SUBSCRIPTION_TIPS_NUM_APP_ID'),
        'app_secret': env('SUBSCRIPTION_TIPS_NUM_APP_SECRET'),
        'token': env('SUBSCRIPTION_TIPS_NUM_TOKEN'),
        'aes_key': env('SUBSCRIPTION_TIPS_NUM_ENCODING_AES_KEY'),
        'can_get_user_info': env('SUBSCRIPTION_TIPS_NUM_CAN_GET_USER_INFO'),
    },
    env('SUBSCRIPTION_BEACHBURG_NUM_ORIGIN_ID'): {
        'app_name': env('SUBSCRIPTION_BEACHBURG_NUM_APP_NAME'),
        'app_id': env('SUBSCRIPTION_BEACHBURG_NUM_APP_ID'),
        'app_secret': env('SUBSCRIPTION_BEACHBURG_NUM_APP_SECRET'),
        'token': env('SUBSCRIPTION_BEACHBURG_NUM_TOKEN'),
        'aes_key': env('SUBSCRIPTION_BEACHBURG_NUM_ENCODING_AES_KEY'),
        'can_get_user_info': env('SUBSCRIPTION_BEACHBURG_NUM_CAN_GET_USER_INFO'),
    },
}

# REDIS
REDIS_LOCATION = f"redis://{env('REDIS_HOST')}:{env('REDIS_PORT')}/{env('REDIS_DB')}"
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": REDIS_LOCATION,
        "TIMEOUT": None,
        "OPTIONS": {
            "CLIENT_CLSAA": "diango_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {"max_connections": 20},
            "PASSWORD": env('REDIS_PWD'),
            "MAX_ENTRIES": 100000,
        },
        'CONN_MAX_AGE': None,
        "KEY_PREFIX": "beachburg",
        "KEY_FUNCTION": lambda key, key_prefix, version: ':'.join([key_prefix, key])
    }
}

# MYSQL
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': env('MYSQL_DATABASE') if not DEBUG else env('MYSQL_TEST_DATABASE'),
        'USER': env('MYSQL_USERNAME'),
        'PASSWORD': env('MYSQL_PASSWORD'),
        'HOST': env('MYSQL_HOST'),
        'PORT': env('MYSQL_PORT'),
        'CONN_MAX_AGE': 600,
        'OPTIONS': {
            'connect_timeout': 30
        },
    }
}

# CELERY
celery_redis_url = f"redis://:{env('REDIS_PWD')}@{env('REDIS_HOST')}:{env('REDIS_PORT')}/{env('REDIS_DB')}"
CELERY_BROKER_URL = celery_redis_url
CELERY_RESULT_BACKEND = celery_redis_url
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TIMEZONE = 'Asia/Shanghai'
CELERY_TASK_RESULT_EXPIRES = 3
CELERY_TASK_ROUTES = {
    'app_subscription_account.tasks.check_user_exists': {'queue': 'celery:check_user_exists'}
}

# 天地图API
BAIDU_MAP_AK = env('BAIDU_MAP_AK')
